import settings from '@/config/settings'
import router from '@/router'
import { store } from '@/store'
import { SmileOutlined, AlertOutlined } from '@ant-design/icons-vue'
import { notification } from 'ant-design-vue'
import { color } from 'echarts'
import { h } from 'vue'

import { read } from '@/api/message'

import newOrder from '@/assets/new-order.mp3'
import cancelOrder from '@/assets/cancel-order.mp3'

const wsUrl = settings.wsUrl + store.state.app.userInfo.id

let audio = null
export default class SocketService {
  static instance = null
  static get Instance() {
    console.log('get Instance', this.instance)
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }
  // 和服务端连接的socket对象
  ws = null
  // 存储回调函数
  callBackMapping = {}
  // 标识是否连接成功
  connected = false
  // 记录重试的次数
  sendRetryCount = 0
  // 重新连接尝试的次数
  connectRetryCount = 0
  //  定义连接服务器的方法
  connect() {
    if (!store.state.app.userInfo.id) return
    // 连接服务器
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket')
    }
    // , 'echo-protocol'
    this.ws = new WebSocket(wsUrl)
    // 连接成功的事件
    this.ws.onopen = () => {
      console.log('连接服务端成功了')
      this.connected = true
      // 重置重新连接的次数
      this.connectRetryCount = 0
    }
    // 1.连接服务端失败
    // 2.当连接成功之后, 服务器关闭的情况
    this.ws.onclose = () => {
      console.log('连接服务端失败')
      this.connected = false
      this.connectRetryCount++
      setTimeout(() => {
        this.connect()
      }, 500 * this.connectRetryCount)
    }
    // 得到服务端发送过来的数据
    this.ws.onmessage = (msg) => {
      openNotification(JSON.parse(msg.data), this)
    }
  }
  // 回调函数的注册
  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack
  }
  // 取消某一个回调函数
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null
  }
  // 发送数据的方法
  send(data) {
    // 判断此时此刻有没有连接成功
    console.log(this.connected)
    if (this.connected) {
      this.sendRetryCount = 0
      try {
        this.ws.send(JSON.stringify(data))
      } catch (e) {
        this.ws.send(data)
      }
    } else {
      this.sendRetryCount++
      setTimeout(() => {
        this.send(data)
      }, this.sendRetryCount * 500)
    }
  }
}
/**
 * 订阅发布模式通知页面更新
 */
class EventEmitter {
  constructor() {
    this.subs = {}
  }
  $on(eventType, fn) {
    if (!this.subs[eventType]) {
      this.subs[eventType] = []
    }
    this.subs[eventType].push(fn)
  }
  //触发事件
  $emit(eventType) {
    if (this.subs[eventType]) {
      this.subs[eventType].forEach((handler) => {
        handler()
      })
    }
  }
}
window.$myEmit = new EventEmitter()

const openNotification = (msgInfo, that) => {
  $myEmit.$emit('query')
  if (msgInfo.actionType == 88) {
    audio && audio.stop && audio.stop()
    audio = new Audio(newOrder)
    audio.play()
  } else if (msgInfo.actionType == 91) {
    audio && audio.stop && audio.stop()
    audio = new Audio(cancelOrder)
    audio.play()
  }
  notification.open({
    message:
      (msgInfo.type == 1 ? '系统消息 ' : '用户消息 ') + msgInfo.createTime,
    description: msgInfo.content || '消息内容丢失',
    style: msgInfo.pcLink
      ? {
          cursor: 'pointer',
          color: '#d41e32',
        }
      : {},
    duration: 0,
    icon: () =>
      h(msgInfo.type == 1 ? AlertOutlined : SmileOutlined, {
        style: 'color: #108ee9',
      }),
    key: msgInfo.id,
    onClick: async () => {
      await read({
        id:msgInfo.id
      })
      router.push(msgInfo.pcLink)
      notification.close(msgInfo.id)
    },
  })
}
